package com.ws.shop.action.admin;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.ws.shop.util.RequestUtil;
import com.ws.shop.util.SpringUtil;

@Controller
@RequestMapping(value="/admin/cache/*")
public class CacheAction extends BaseAdminAction{
	@Autowired
	private CacheManager cacheManager;
	
	@RequestMapping(value="index.jhtml",method=RequestMethod.GET)
	public String index(HttpServletRequest request){
		return "cache_index";
	}
	
	@RequestMapping(value="flush.jhtml",method=RequestMethod.GET)
	public String flush(HttpServletRequest request,HttpServletResponse response){
		String flush = RequestUtil.getStringParameter(request, "flush", "page");
		if("all".equals(flush)){
			flushPage();
			flushData();
			return this.ajaxJsonSuccessMessage(response, "成功刷新所有缓存");
		}else if("page".equals(flush)){
			flushPage();
			return this.ajaxJsonSuccessMessage(response, "成功刷新页面缓存");
		}else if("data".equals(flush)){
			flushPage();
			return this.ajaxJsonSuccessMessage(response, "成功刷新数据缓存");
		}
	    return this.ajaxJsonErrorMessage(response, "刷新操作数据有误");
	}
	
	public void flushPage(){
		SpringUtil.getBeanFromAdminApplicationContext(FreeMarkerConfigurer.class).getConfiguration().clearTemplateCache();
		SpringUtil.getBeanFromFrontApplicationContext(FreeMarkerConfigurer.class).getConfiguration().clearTemplateCache();
		SpringUtil.getBean(FreeMarkerConfigurer.class).getConfiguration().clearTemplateCache();
	}
	
	public void flushData(){
		Collection<String> cacheNames = cacheManager.getCacheNames();
		for(String cacheName : cacheNames){
			cacheManager.getCache(cacheName).clear();
		}
	}
}
